<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="用源码与图解的方式详细探究 Sentinel 调用上下文环境是如何管理的。 本节将详细介绍 Sentienl 的上下文环境管理机制。 1、Sentinel Context 调用上下文环境管理我们从  sentinel-apache-dubbo-adapter 模块的 SentinelDubboProviderFilter 的实现中不难看出，在其入口处会首先调用 ContextUtil.enter(">
<meta property="og:type" content="article">
<meta property="og:title" content="Sentinel 调用上下文环境实现原理">
<meta property="og:url" content="https://www.codingw.net/posts/e7bbdda0.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="用源码与图解的方式详细探究 Sentinel 调用上下文环境是如何管理的。 本节将详细介绍 Sentienl 的上下文环境管理机制。 1、Sentinel Context 调用上下文环境管理我们从  sentinel-apache-dubbo-adapter 模块的 SentinelDubboProviderFilter 的实现中不难看出，在其入口处会首先调用 ContextUtil.enter(">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020011209183558.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200112092204338.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200112092324439.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200112092345428.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200112092639143.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200112092720275.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-09-21T14:45:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:37:38.976Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/2020011209183558.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/e7bbdda0.html"/>





  <title>Sentinel 调用上下文环境实现原理 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/e7bbdda0.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Sentinel 调用上下文环境实现原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-21T22:45:35+08:00">
                2020-09-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/e7bbdda0.html" class="leancloud_visitors" data-flag-title="Sentinel 调用上下文环境实现原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>用源码与图解的方式详细探究 Sentinel 调用上下文环境是如何管理的。</p>
<p>本节将详细介绍 Sentienl 的上下文环境管理机制。</p>
<h2 id="1、Sentinel-Context-调用上下文环境管理"><a href="#1、Sentinel-Context-调用上下文环境管理" class="headerlink" title="1、Sentinel Context 调用上下文环境管理"></a>1、Sentinel Context 调用上下文环境管理</h2><p>我们从  sentinel-apache-dubbo-adapter 模块的 SentinelDubboProviderFilter 的实现中不难看出，在其入口处会首先调用 ContextUtil.enter(resourceName, application) 。那我们就从该方法开始来探究上下文环境管理机制。</p>
<p>说到 Sentinel 的调用上下文环境，那调用上下文环境中会保存哪些信息呢？我们先来看看 Context。</p>
<h4 id="1-1-Context-详解"><a href="#1-1-Context-详解" class="headerlink" title="1.1 Context 详解"></a>1.1 Context 详解</h4><p>Context 类图如下：<br><img src="https://img-blog.csdnimg.cn/2020011209183558.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<ul>
<li><p>Context<br>其核心属性与核心方法如下：</p>
<ul>
<li>String name<br>Sentinel 调用上下文环境的名称。</li>
<li>DefaultNode entranceNode<br>调用链的入口节点信息。</li>
<li>Entry curEntry<br>调用链中当前节点的信息。</li>
<li>boolean async<br>是否是异步调用上下文环境。</li>
<li>Entry<br>保存当前的调用信息，其主要核心属性：</li>
<li>private long createTime<br>资源调用的时间戳。</li>
<li>private Node curNode<br>该资源所对应的实时采集信息。</li>
<li>protected ResourceWrapper resourceWrapper<br>资源对象。</li>
</ul>
</li>
<li><p>CtEntry<br>同步调用调用信息封装对象。</p>
</li>
<li><p>AsyncEntry<br>异步调用调用信息的封装对象。</p>
</li>
</ul>
<p>对应的核心方法将在下文具体用到时再详细介绍。</p>
<h4 id="1-2-创建调用上下文环境"><a href="#1-2-创建调用上下文环境" class="headerlink" title="1.2 创建调用上下文环境"></a>1.2 创建调用上下文环境</h4><p>ContextUtil#enter</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Context <span class="title">enter</span><span class="params">(String name, String origin)</span> </span>&#123;  <span class="comment">// @1</span></span><br><span class="line">	<span class="keyword">if</span> (Constants.CONTEXT_DEFAULT_NAME.equals(name)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ContextNameDefineException(</span><br><span class="line">                <span class="string">&quot;The &quot;</span> + Constants.CONTEXT_DEFAULT_NAME + <span class="string">&quot; can&#x27;t be permit to defined!&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> trueEnter(name, origin);   <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先我们来看一下其参数：</p>
<ul>
<li>String name<br>上下文环境 Context 的名称。</li>
<li>String origin<br>该参数的含义在介绍集群限流时会详细介绍，从 dubbo 模块的适配来看，通常该值会传入当前应用的 application 名称。</li>
</ul>
<p>代码@2：通过调用内部的 trueEnter 方法。</p>
<p>在进入 trueEnter 方法之前，我们先来看一下 ContextUtil 中两个最核心的属性：<br><img src="https://img-blog.csdnimg.cn/20200112092204338.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>首先使用 ThreadLocal 对象来存储线程上下文环境对象 Context。Map&lt;String, DefaultNode&gt; contextNameNodeMap ，其键为 context 的名称，用来缓存其对应的 EntranceNode 。</p>
<p>ContextUtil#trueEnter</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">static</span> Context <span class="title">trueEnter</span><span class="params">(String name, String origin)</span> </span>&#123;</span><br><span class="line">    Context context = contextHolder.get();   <span class="comment">// @1 </span></span><br><span class="line">    <span class="keyword">if</span> (context == <span class="keyword">null</span>) &#123;</span><br><span class="line">	Map&lt;String, DefaultNode&gt; localCacheNameMap = contextNameNodeMap;</span><br><span class="line">        DefaultNode node = localCacheNameMap.get(name);   <span class="comment">// @2</span></span><br><span class="line">        <span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">if</span> (localCacheNameMap.size() &gt; Constants.MAX_CONTEXT_NAME_SIZE) &#123;   <span class="comment">// @3</span></span><br><span class="line">                 	setNullContext();</span><br><span class="line">               	 	<span class="keyword">return</span> NULL_CONTEXT;</span><br><span class="line">           	 &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                	<span class="keyword">try</span> &#123;</span><br><span class="line">                    		LOCK.lock();</span><br><span class="line">                    		node = contextNameNodeMap.get(name);   <span class="comment">// @4</span></span><br><span class="line">                    		<span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">                        		<span class="keyword">if</span> (contextNameNodeMap.size() &gt; Constants.MAX_CONTEXT_NAME_SIZE) &#123;  </span><br><span class="line">                            			setNullContext();</span><br><span class="line">                            			<span class="keyword">return</span> NULL_CONTEXT;</span><br><span class="line">                        		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                           			 node = <span class="keyword">new</span> EntranceNode(<span class="keyword">new</span> StringResourceWrapper(name, EntryType.IN), <span class="keyword">null</span>);  <span class="comment">// @5</span></span><br><span class="line">                            			<span class="comment">// Add entrance node.</span></span><br><span class="line">                            			Constant.ROOT.addChild(node);                                                                                     <span class="comment">// @6</span></span><br><span class="line">						Map&lt;String, DefaultNode&gt; newMap = <span class="keyword">new</span> HashMap&lt;&gt;(contextNameNodeMap.size() + <span class="number">1</span>);</span><br><span class="line">                            			newMap.putAll(contextNameNodeMap);</span><br><span class="line">                            			newMap.put(name, node);</span><br><span class="line">                            			contextNameNodeMap = newMap;</span><br><span class="line">                        		&#125;</span><br><span class="line">                    		&#125;</span><br><span class="line">                	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    		LOCK.unlock();</span><br><span class="line">               		&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        context = <span class="keyword">new</span> Context(node, name);    <span class="comment">// @7</span></span><br><span class="line">        context.setOrigin(origin);</span><br><span class="line">        contextHolder.set(context);    <span class="comment">// @8</span></span><br><span class="line">   &#125;</span><br><span class="line">  <span class="keyword">return</span> context;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：从 threadLocal 中获取 Context 对象，线程首次获取时为空。</p>
<p>代码@2：根据 context 的名称尝试从缓存中去找对应的 Node，通常是 EntranceNode。即用来表示入口的节点Node 为 EntranceNode。</p>
<p>代码@3：如果 localCacheNameMap 已缓存的对象容量默认超过2000，则不纳入 Sentinel 限流，熔断等机制中来，即一个应用，默认不能定义 2000个 资源统计入口，以 一个 Dubbo 服务为例，一个 Dubbo 服务应用，如果超过2000个服务，则超过的部分不会应用 Sentinel 限流与熔断机制。</p>
<p>代码@4：锁应用的经典场景，dubbo check。</p>
<p>代码@5：为该 context name 创建一个对应的 EntranceNode。</p>
<p>代码@6：将创建的 EntranceNode 加入到根节点的子节点中，稍后重点讨论一下。</p>
<p>代码@7：创建 Context 对象，将 Context 对象中的入口节点设置为 新创建的 EntranceNode。</p>
<p>代码@8：将新创建的 Context 对象存入当前线程本地环境变量中(ThreadLocal)。</p>
<p>接下来先来探讨代码@6 Constants.ROOT.addChild(node)。</p>
<p>在 Sentinel 中，会定义一个固定根节点，其定义如下：<br><img src="https://img-blog.csdnimg.cn/20200112092324439.png" alt="在这里插入图片描述"><br>其资源名称为：machine-root。addChild 方法就是将节点添加到如下数据结构中：<br><img src="https://img-blog.csdnimg.cn/20200112092345428.png" alt="在这里插入图片描述"></p>
<h4 id="1-3-移除调用上下文环境"><a href="#1-3-移除调用上下文环境" class="headerlink" title="1.3 移除调用上下文环境"></a>1.3 移除调用上下文环境</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">exit</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Context context = contextHolder.get();</span><br><span class="line">    <span class="keyword">if</span> (context != <span class="keyword">null</span> &amp;&amp; context.getCurEntry() == <span class="keyword">null</span>) &#123;</span><br><span class="line">        contextHolder.set(<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>退出当前上下文环境，这里有一个条件就是当前的上下文环境的当前调用节点已经退出，否则无法移除，故使用建议：ContextUtil . exit 一定要在持有的 Entry 退出之后再调用。</p>
<span id="more"></span>

<h4 id="1-4-异步上下文环境切换"><a href="#1-4-异步上下文环境切换" class="headerlink" title="1.4 异步上下文环境切换"></a>1.4 异步上下文环境切换</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">runOnContext</span><span class="params">(Context context, Runnable f)</span> </span>&#123;</span><br><span class="line">	Context curContext = replaceContext(context);  <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">		f.run();  <span class="comment">// @2</span></span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        replaceContext(curContext);  <span class="comment">// @3</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里是异步调用上下文环境切换的实现原理，我们知道存在 ThreadLocal 中的数据是无法跨线程访问的，故一个线程中启动另外一个线程，上下文环境是无法直接被传递的，Sentinel 的思想是为先创建的线程再创建一个 Context，在运行子线程时，调用 runOnContext 来切换上下文环境。</p>
<p>Context 就介绍到这里了，我们接下来再来看一个与上下文环境管理密切相关的 Sentinel Slot 处理器：NodeSelectorSlot，通常也是 Sentinel Slot 处理链的第一个节点。</p>
<h2 id="2、NodeSelectorSlot"><a href="#2、NodeSelectorSlot" class="headerlink" title="2、NodeSelectorSlot"></a>2、NodeSelectorSlot</h2><h4 id="2-1-NodeSelectorSlot-调用链概述"><a href="#2-1-NodeSelectorSlot-调用链概述" class="headerlink" title="2.1 NodeSelectorSlot 调用链概述"></a>2.1 NodeSelectorSlot 调用链概述</h4><p>从该类的注释可以得出如下的结论：该类的作用是构建一颗虚拟调用树，我们接下来以一个Dubbo调用示例来说明。<br><img src="https://img-blog.csdnimg.cn/20200112092639143.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>正如上图所示：应用 A 向应用 order-servie 服务发起一个 RPC 服务，下订单，order-service 应用引入了 sentinel-apache-dubbo-adapter 相关依懒，会执行 SentinelDubboProviderFilter 过滤器，调用 Sentinel 相关的方法，对资源进行保护，然后下单服务中，首先会操作数据库，将本次数据库操作定义为资源：insertOrderSQL，然后再操作 redis，redis 的操作命名为资源 setRedisOp。其对应在内存中会生成如下调用链的结构图。<br><img src="https://img-blog.csdnimg.cn/20200112092720275.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>那上面这个调用链保存在线程上下文环境中，即 ThreadLocal 中。在 Sentinel 中使用 Node 来表示一个一个调用节点，其中 EntranceNode  表示调用链的入口，DefaultNode 表示普通节点，ClusterNode 表示集群节点，即同一个资源会统计整个集群中的信息。</p>
<p>从该类的注释我们可以得出上述的结论，接下来我们从源码的角度对其进行分析与理解。</p>
<h4 id="2-2-源码分析-NodeSelectorSlot"><a href="#2-2-源码分析-NodeSelectorSlot" class="headerlink" title="2.2 源码分析 NodeSelectorSlot"></a>2.2 源码分析 NodeSelectorSlot</h4><p>NodeSelectorSlot 中只声明了一个唯一的成员变量，其声明如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> Map&lt;String, DefaultNode&gt; map = <span class="keyword">new</span> HashMap&lt;String, DefaultNode&gt;(<span class="number">10</span>);</span><br></pre></td></tr></table></figure>
<p>定义一个 Map，其键为上下文环境 Context 的名称，通常是进入节点的名称，例如上面提到的 EntranceNode（ dubbo:provider:com.a.b.OrderService:saveOrder(java.lang.String)）。</p>
<blockquote>
<p>注意：一个 NodeSelectorSlot 对象会被多个线程使用，其共享的维度为资源，即多个线程进入同一个资源保护的代码时，执行的是同一个 NodeSelectorSlot 对象。详细实现请参考上文中 CtSph # lookProcessChain 部分详解。</p>
</blockquote>
<p>接下来重点看一下 NodeSelectorSlot 的核心方法 entry。</p>
<p>NodeSelectorSlot#entry</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">entry</span><span class="params">(Context context, ResourceWrapper resourceWrapper, Object obj, <span class="keyword">int</span> count, <span class="keyword">boolean</span> prioritized, Object... args)</span> <span class="comment">// @1</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    DefaultNode node = map.get(context.getName());   <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;                                                       <span class="comment">// @3</span></span><br><span class="line">	    <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;                                          <span class="comment">// @4</span></span><br><span class="line">	        node = map.get(context.getName());</span><br><span class="line">                <span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">			node = <span class="keyword">new</span> DefaultNode(resourceWrapper, <span class="keyword">null</span>);    <span class="comment">// @5</span></span><br><span class="line">              	        HashMap&lt;String, DefaultNode&gt; cacheMap = <span class="keyword">new</span> HashMap&lt;String, DefaultNode&gt;(map.size());</span><br><span class="line">                	cacheMap.putAll(map);</span><br><span class="line">                	cacheMap.put(context.getName(), node);</span><br><span class="line">                	map = cacheMap;</span><br><span class="line">               	 	<span class="comment">// Build invocation tree</span></span><br><span class="line">                	((DefaultNode) context.getLastNode()).addChild(node);   <span class="comment">// @6</span></span><br><span class="line">          	&#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    context.setCurNode(node);                                                                  <span class="comment">// @7</span></span><br><span class="line">    fireEntry(context, resourceWrapper, node, count, prioritized, args);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：我们先来看看其参数：</p>
<ul>
<li>Context context<br>调用上下文环境，该对象存储在 ThreadLocal，其名称在调用链的入口处设置。</li>
<li>ResourceWrapper resourceWrapper<br>资源的包装类，注意留意其 equals 与 hashCode 方法，判断两个对象是否相等的依据是资源名<br>称是否相同。</li>
<li>Object obj<br>参数。</li>
<li>int count<br>本次需要消耗的令牌数量。</li>
<li>boolean prioritized<br>请求是否按优先级排列。</li>
<li>Object… args<br>额外参数。</li>
</ul>
<p>代码@2：如果缓存中存在对应该上下文环境的节点，则直接使用，并将其节点设置当前调用上下文的当前节点中(Context)。</p>
<p>代码@3：如果节点为空，则进入到节点创建流程，此过程需要加锁，见代码@4。</p>
<p>代码@5：创建一个新的 DefaultNode 。</p>
<p>代码@6：构建调用链，由于 NodeSelectorSlot 是第一个进入的处理器，故此时 Context 的 curEntry 为 null ，故这里就是创建与的上下文环境名称对应的节点会被添加到 ContextUtil 的 entry 创建的调用链入口节点(EntranceNode)，然后顺便更新 Context 中的 Entry curEntry 属性，即再次验证了上面的图。</p>
<p>我们来总结一下 NodeSelectorSlot 作用：从官方的注释来看：构建一条调用链，更直接一点就是设置 Context 的 curEntry 属性。</p>
<p>关于 Sentinel 调用上下文环境实现原理就介绍到这里了。</p>
<p>思考题：首先在这里先“剧透”一下，Node 在 Sentinel 中的作用是持有资源的实时统计信息，将在下一篇文章介绍 StatisticSlot 时详细介绍。 NodeSelectorSlot 中的  Map&lt;String, DefaultNode&gt; 中的键为什么是 Context 的 名称呢？这样设计的目的是什么，能有什么好处？针对该问题将在笔者维护的知识星球中与各位星友展开讨论，欢迎您的加入。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/a815ae71.html" rel="next" title="Sentinel 系统自适应限流原理剖析与实战指导">
                <i class="fa fa-chevron-left"></i> Sentinel 系统自适应限流原理剖析与实战指导
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/5f8f7185.html" rel="prev" title="源码分析 Sentinel 实时数据采集实现原理">
                源码分析 Sentinel 实时数据采集实现原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81Sentinel-Context-%E8%B0%83%E7%94%A8%E4%B8%8A%E4%B8%8B%E6%96%87%E7%8E%AF%E5%A2%83%E7%AE%A1%E7%90%86"><span class="nav-number">1.</span> <span class="nav-text">1、Sentinel Context 调用上下文环境管理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-Context-%E8%AF%A6%E8%A7%A3"><span class="nav-number">1.0.1.</span> <span class="nav-text">1.1 Context 详解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-%E5%88%9B%E5%BB%BA%E8%B0%83%E7%94%A8%E4%B8%8A%E4%B8%8B%E6%96%87%E7%8E%AF%E5%A2%83"><span class="nav-number">1.0.2.</span> <span class="nav-text">1.2 创建调用上下文环境</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-%E7%A7%BB%E9%99%A4%E8%B0%83%E7%94%A8%E4%B8%8A%E4%B8%8B%E6%96%87%E7%8E%AF%E5%A2%83"><span class="nav-number">1.0.3.</span> <span class="nav-text">1.3 移除调用上下文环境</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-4-%E5%BC%82%E6%AD%A5%E4%B8%8A%E4%B8%8B%E6%96%87%E7%8E%AF%E5%A2%83%E5%88%87%E6%8D%A2"><span class="nav-number">1.0.4.</span> <span class="nav-text">1.4 异步上下文环境切换</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81NodeSelectorSlot"><span class="nav-number">2.</span> <span class="nav-text">2、NodeSelectorSlot</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-NodeSelectorSlot-%E8%B0%83%E7%94%A8%E9%93%BE%E6%A6%82%E8%BF%B0"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 NodeSelectorSlot 调用链概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90-NodeSelectorSlot"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 源码分析 NodeSelectorSlot</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
